/**
 * 创建延时任务
 */
export const delay = (delay = 1000) => {
  return new Promise<void>((resolve) => {
    const timeout = setTimeout(() => {
      clearTimeout(timeout);
      resolve();
    }, delay);
  });
};

/**
 * 创建循环任务
 */
export const loopTask = (
  fn: (done: () => void, stop: () => void) => void,
  delay = 60,
  immediate = false
) => {
  let timeout: number;
  const stop = () => timeout && clearTimeout(timeout);
  const done = () => {
    stop();
    timeout = setTimeout(taskFn, delay);
  };
  const taskFn = () => fn(done, stop);
  immediate ? taskFn() : done();
  return stop;
};
